﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataModel.Managers.SubManage;
using UniversityPortal.Models;
using UniversityPortal.Models.User;

using DataModel.Models;
using DataModel.Managers;
using System.Web.Security;

namespace UniversityPortal.Controllers
{
    public class UserController : Controller
    {

        //[UAuthorize(UserRoles = "Admin")]
        public ActionResult Index()
        {
            return View();
        }

        //[UAuthorize(UserRoles = "Admin")]
        public ActionResult DeleteUser()
        {
            return View();
        }

        //[UAuthorize(UserRoles = "Admin")]
        public ActionResult CreateUser()
        {
            return View(new RegisterModel());
        }

        #region Admin
        [HttpPost]
        //[UAuthorize(UserRoles = "Admin")]
        public ActionResult CreateAdmin(RegisterModel rm)
        {
            if (ModelState.IsValid)
            {
                new UserManager().CreateAdmin(rm.Email, rm.LastName, rm.FirstName, rm.FamilyName);
            }
            return RedirectToAction("CreateUser");
        }
        #endregion

        #region Student

        public ActionResult GetDepartment()
        {
            DepartmentManager dm = new DepartmentManager();

            List<SelectListItem> departments = new List<SelectListItem>();
            foreach (var department in dm.GetAllDepartments())
            {
                departments.Add(new SelectListItem()
                {
                    Text = department.ShortName,
                    Value = department.DepartmentID.ToString()
                });
            }

            return PartialView("GetDepartment", departments.AsEnumerable());
        }

        public ActionResult GetSpecialities()
        {
            DepartmentManager dm = new DepartmentManager();
            List<SelectListItem> specialities = new List<SelectListItem>();
            Guid id = Guid.Parse(Request.QueryString[0]);
            foreach (var spec in dm.GetDepartmentSpecialities(id))
            {
                specialities.Add(new SelectListItem()
                {
                    Text = spec.ShortName,
                    Value = spec.SpecialityID.ToString()
                });
            }
            return PartialView("GetSpecialities", specialities);
        }

        public ActionResult RegisterStudent()
        {
            List<SelectListItem> groupList = new List<SelectListItem>();
            Guid id = Guid.Parse(Request.QueryString[0]);
            var gm = new GroupManager();
            foreach (var gr in gm.GetGroupsInSpeciality(id))
            {
                groupList.Add(new SelectListItem()
                {
                    Text = gr.Number.ToString(),
                    Value = gr.Id.ToString()
                });
            }
            return PartialView("RegisterStudent", groupList);
        }

        [HttpPost]
        //[UAuthorize(UserRoles = "Admin")]
        public ActionResult CreateStudent(RegisterModel rm)
        {
            if (ModelState.IsValid)
            {
                Guid groupID = Guid.Parse(Request.Form["Group"]);
                new UserManager().CreateStudent(rm.Email, rm.LastName, rm.FirstName, rm.FamilyName, groupID);
            }
            return RedirectToAction("CreateUser");
        }

        #endregion

        #region Professors

        public ActionResult RegisterProfessor()
        {
            UniversityPortalEntities entityModel = new UniversityPortalEntities();
            List<SelectListItem> degreeList = new List<SelectListItem>();
            List<SelectListItem> chairList = new List<SelectListItem>();
            foreach (var degree in entityModel.Degrees)
            {
                degreeList.Add(new SelectListItem()
                {
                    Text = degree.name,
                    Value = degree.ID.ToString()
                });
            }

            foreach (var chair in entityModel.Chairs)
            {
                chairList.Add(new SelectListItem()
                {
                    Text = chair.shortName,
                    Value = chair.ID.ToString()
                });
            }

            ViewBag.Chairs = chairList.AsEnumerable();
            ViewBag.Degrees = degreeList.AsEnumerable();
            return PartialView("RegisterProfessor");
        }

        [HttpPost]
        //[UAuthorize(UserRoles = "Admin")]
        public ActionResult CreateProfessor(RegisterModel rm)
        {
            if (ModelState.IsValid)
            {
                Guid degreeID = Guid.Parse(Request.Form["Degree"]);
                Guid chairID = Guid.Parse(Request.Form["Chair"]);
                new UserManager().CreateProfessor(rm.Email, rm.LastName, rm.FirstName, rm.FamilyName, degreeID, chairID);
            }
            return RedirectToAction("CreateUser");
        }

        #endregion

        public bool ChangeUserLogin()
        {
            string newLogin = (Request.QueryString.Count != 0)?Request.QueryString[0]:null;
            if (newLogin != null && (newLogin.Length > 3) && (newLogin.IndexOf(' ') < 0))
            {
                UserManager userManager = new UserManager();
                userManager.ChangeUserLogin(Guid.Parse(Session["userID"].ToString()), newLogin);

                HttpCookie cookie = Request.Cookies["UniversityPortalUserLoginCookie"];
                if (cookie != null)
                {
                    string oldValue = cookie.Value;
                    string[] oldValues = oldValue.Split(' ');
                    cookie.Value = string.Format("{0} {1} {2}", newLogin, oldValue[1], oldValue[2]);
                    cookie.Expires = DateTime.Now.AddYears(2);
                    Response.Cookies.Add(cookie);
                }
                return true;
            }
            return false;
        }

        public ActionResult ChangePassword()
        {
            return View(new ChangePasswordModel());
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                Guid userID = Guid.Parse(Session["userID"].ToString());
                UserManager userManager = new UserManager();
                if (userManager.ChangeUserPassword(userID, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePassword");
                }
                else
                {
                    return RedirectToAction("ChangePassword");
                }
            }
            return RedirectToAction("ChangePassword");
        }

        [HttpPost]
        public ActionResult Login(LogInModel loginModel, string returnUrl)
        {
            AuthenticationManager auth = new AuthenticationManager();
            if (auth.IsValid(loginModel.Login, loginModel.Password))
            {
                if (loginModel.Remember == true)
                {
                    HttpCookie cookie = new HttpCookie("UniversityPortalUserLoginCookie");
                    cookie.Value = string.Format("{0} {1} {2}", loginModel.Login, loginModel.Password, "True");
                    cookie.Expires = DateTime.Now.AddYears(2);
                    Response.Cookies.Add(cookie);
                }

                var um = new UserManager();
                UserModel user = um.GetUser(loginModel.Login);
                if (user.Roles.Any(rl => rl.Name == "Student"))
                {
                    Session["username"] = string.Format("{0} {1} {2}, group {3}", user.LastName, user.FirstName, user.FamilyName, um.GetStudentGroup(user.Login));
                }
                else
                {
                    Session["username"] = string.Format("{0} {1} {2}", user.LastName, user.FirstName, user.FamilyName);
                }
                Session["userID"] = um.GetUserID(user.Login);
                Session["rememberuser"] = loginModel.Remember.ToString();
            }
            if ((returnUrl == null) || (returnUrl == String.Empty))
            {
                return RedirectToAction("Index", "Home");
            }
            return Redirect(returnUrl);
        }

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        public ActionResult Logoff()
        {
            if (((string)Session["rememberuser"]) == "True")
            {
                // delete cookie
                HttpCookie cookie = new HttpCookie("UniversityPortalUserLoginCookie");
                cookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(cookie);
            }
            Session.Clear();
            return RedirectToAction("Login");
        }

    }
}
